#!/usr/bin/env python3

import os
import subprocess
import sys

# 设置环境变量
os.environ['PROJ_ROOT'] = '/home/apachee/trunk/Crystal/CrystalFlowAnalyzer/a9soc'

# 读取原始文件列表
file_list_path = '/home/apachee/trunk/Crystal/CrystalFlowAnalyzer/a9soc/design/usb2/src/DWC_usb3.lst'
with open(file_list_path, 'r') as f:
    lines = f.readlines()

print(f"Total files in list: {len(lines)}")

# 逐个测试文件
for i, line in enumerate(lines[:10]):  # 只测试前10个文件
    line = line.strip()
    if not line or line.startswith('#') or line.startswith('//') or line.startswith('component:') or line.startswith('library:') or line.startswith('files:'):
        print(f"Skipping line {i+1}: {line}")
        continue
    
    # 创建单文件测试列表
    test_file = f'test_file_{i+1}.lst'
    with open(test_file, 'w') as f:
        f.write(line)
    
    print(f"\nTesting file {i+1}: {line}")
    
    # 检查文件是否存在
    resolved_path = line.replace('$PROJ_ROOT', '/home/apachee/trunk/Crystal/CrystalFlowAnalyzer/a9soc')
    if os.path.exists(resolved_path):
        print(f"  File exists: {resolved_path}")
    else:
        print(f"  File does not exist: {resolved_path}")
        continue
    
    # 运行moparse
    cmd = ['./moparse', '-f', test_file, '-o', f'test_file_{i+1}.modb']
    print(f"  Running command: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        if result.returncode == 0:
            print(f"  SUCCESS: File {i+1} processed successfully")
            # 检查生成的modb文件
            if os.path.exists(f'test_file_{i+1}.modb'):
                size = os.path.getsize(f'test_file_{i+1}.modb')
                print(f"  Generated MODB file size: {size} bytes")
            else:
                print(f"  WARNING: MODB file was not generated")
        else:
            print(f"  ERROR: File {i+1} failed with return code {result.returncode}")
            print(f"  STDERR: {result.stderr}")
            break
    except subprocess.TimeoutExpired:
        print(f"  TIMEOUT: File {i+1} timed out")
        break
    except Exception as e:
        print(f"  EXCEPTION: File {i+1} failed with exception: {e}")
        break

print("\nTest completed")